/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 * 
 * @file:   Album.js
 * @path:   js-src/album/
 * @author: jiegang@qiyi.com
 * @date:   2015-01-11
 */

define(
    '../entrance_record/Ancestor',['require','exports','module'],function(require, exports, module) {
        window.Ancestor = window.Ancestor || {
            version: '1.0'
        };
        window.SystemDialog = (function () {
            var doHandler = null;
            var _initAlert = false;
            var _initConfirm = false;

            function initAlertDlg() {
                if (!_initAlert) {
                    if ($("#epg_alert_dlg").length == 0) {
                        $('body').append('<div id="epg_alert_dlg"><div sign="detail"></div></div>');
                    }
                    $("#epg_alert_dlg").dialog({
                        title: "epg系统提醒",
                        autoOpen: false,
                        width: 400,
                        modal: true,
                        dialogClass: 'alert',
                        resizable: false,
                        closeOnEscape:false,
                        buttons: [
                            {
                                text: "确认",
                                click: function () {
                                    $(this).dialog("close");
                                }
                            }
                        ]
                    })
                    _initAlert = true;
                }
                console.log("_initAlert:" + _initAlert);
            }

            function initConfirmDlg() {
                if (!_initConfirm) {
                    if ($("#epg_confirm_dlg").length == 0) {
                        $('body').append('<div id="epg_confirm_dlg"><div sign="detail"></div></div>');
                    }
                    $("#epg_confirm_dlg").dialog({
                        title: "epg系统确认",
                        autoOpen: false,
                        width: 400,
                        modal: true,
                        dialogClass: 'alert',
                        resizable: false,
                        closeOnEscape:false,
                        buttons: [
                            {
                                text: "确认",
                                click: function () {
                                    $(this).dialog("close");
                                    doHandler(true);
                                }
                            },
                            {
                                text: "取消",
                                click: function () {
                                    $(this).dialog("close");
                                    doHandler(false);
                                }
                            }
                        ]
                    });
                    $("div[aria-describedby=epg_confirm_dlg]").find("button:eq(1)").addClass("btn btn-primary");
                    $("div[aria-describedby=epg_confirm_dlg]").find("button:eq(2)").addClass("btn");
                    _initConfirm = true;
                }
                console.log("_initConfirm:" + _initConfirm);
            }

            function queryAlert(msg) {
                initAlertDlg()
                $("#epg_alert_dlg").find("div[sign=detail]").html(msg);
                $("#epg_alert_dlg").dialog("open");
            }

            function queryConfirm(msg, callback,btnNameObj) {
                initConfirmDlg();
                $("#epg_confirm_dlg").find("div[sign=detail]").html(msg);
                var btnExtend = $.extend(true,{"btn_ok":"确认","btn_cancel":"取消"},btnNameObj);
                if( "btn_ok" in btnExtend){
                    $("div[aria-describedby=epg_confirm_dlg]").find("button:eq(1)").html(btnExtend["btn_ok"])
                }
                if( "btn_cancel" in btnExtend){
                    $("div[aria-describedby=epg_confirm_dlg]").find("button:eq(2)").html(btnExtend["btn_cancel"])
                }
                $("#epg_confirm_dlg").dialog("open");
                doHandler = function (flag) {
                    if (typeof(callback) == "function") {
                        callback(flag);
                    }
                }
            }

            return {
                queryAlert: queryAlert,
                queryConfirm: queryConfirm
            }
        })();

    }
);
define(
    '../entrance_record/Ancestor.Auth',['require','exports','module'],function (require, exports, module) {
        Ancestor.Auth = (function () {
            var baseInfo = {
                authUrl: '/api/permission',
                loginUrl: 'http://lego.iqiyi.com/login?url=http://lego.iqiyi.com%2F',
                url403: 'http://lego.iqiyi.com/common/403.jsp',
                loginOut: 'http://lego.iqiyi.com/logout',
                navListUrl: 'http://ulive.lego.iqiyi.com/live-web/services/liveNav.do',
                authInfo: null,
                tips: 0 //0 304页面提示 1头部标签提示
            }
            var jump2TargetPage = function (url) {
                window.location.href = url;
            }
            var getDev = function () {
                return parseInt(Com.cookie.get('dev'));
            };

            function getVersion(){
                return "4.3.180";
            }

            function setWaring(tips) {
                var warning = '<div  style="display:block;position: fixed;top: 5px;left: 10%;width: 80%;z-index: 100000;text-align: center;height: 26px;line-height: 26px;color: red;background: #fff1d3;margin-bottom: 16px;text-shadow: 0 1px 0 rgba(255,255,255,0.5);"><strong>提示!</strong> ' + tips + '</div>';
                return warning;
            }

            // ajax 请求
            var getAuthData = function (options, callback) {
                options = options || {};
                var url = url || Com.url.parse(window.location.href)['path'];
                var tempBaseInfo = $.extend(true,{url:url} , baseInfo, options);
                Ancestor.Dao.ajax({
                    url: tempBaseInfo.authUrl,
                    dataType: 'json',
                    method: 'get',
                    cache: false,
                    //async: false,
                    data: {'uri': tempBaseInfo.url.split('?')[0]},
                    success: function (data) {
                        //console.log(data);
                        if (options.tips) {
                            //   if (baseInfo.tips) {
                            if (data.code == 'A00304')
                                callback.call(this, 1);   // 无权限
                            else
                                callback.call(this, null); // 有权限
                            return;
                        }
                        switch (data.code) {
                            case 'A00000': // 已登陆
                                tempBaseInfo.authInfo = data.data;
                                var newDev = 0;
                                if (tempBaseInfo.authInfo.devMode) {
                                    newDev = 1
                                }
                                var dev = getDev();
                                showLogInfo( tempBaseInfo );
                                callback.call(this, "suc")
                                if (dev == NaN || dev != newDev) {
                                    Com.cookie.set('dev', newDev);
                                    window.location.reload();
                                }
                                break;
                            case 'A00303': // 未登陆
                            case 'A00401':
                                jump2TargetPage(tempBaseInfo.loginUrl);
                                break;

                            case 'A00304': // 无权限
                                //jump2TargetPage(baseInfo.url403);
                                var warning = setWaring('sorry,您没有操作本页面的权限！');
                                $('body').html('');
                                $('body').html(warning);
                                break;
                        }
                    },
                    error: function (data) {
                        var warning = setWaring('网络故障,<a href="javascript:void(0);" onclick = "window.location.reload();">请重刷！</a>');
                        $('body').html(warning);
                    }
                }, "/permission")

            }

            function queryNavList(baseInfo){
                var request = {};
                request.url = baseInfo.navListUrl;
                request.type = 'get';
                request.params = {};
                request.needCookie = true;
                request = JSON.stringify(request);
                Ancestor.Dao.redirectRequest({request: request} , function(data){
                    if(!data) {
                        console.warn(" 获取导航条失败!")
                        return;
                    }
                    Ancestor.Util.buildMenu(  data )
                } )
            }

            function showLogInfo(baseInfo) {
                var epg_version = auth.version() + (auth.dev() ? "_test" : "_production");
                Ancestor.Util.buildHeader();
                Ancestor.Util.buildUserInfo(baseInfo);
                Ancestor.Util.buildFooter(epg_version);
                $("#BackToTopButton").bind("click",function(){
                    $("html,body").animate({"scrollTop":0})
                })
                $(window).bind('scroll', function () {
                    Com.page.scrollToTop($("#BackToTopButton"));
                });
                queryNavList(baseInfo)
            }

            return{
                getAuthData: getAuthData,
                baseInfo: baseInfo,
                jump2TargetPage: jump2TargetPage,
                dev: getDev, //开发环境
                version:getVersion
            };
        })();
        var auth = Ancestor.Auth;
        var dev = auth.dev();
        window.auth = auth;
        window.dev = dev;
        console.log(" window.auth done");
    }
);
/**
 * Copyright 2013 Qiyi Inc. All rights reserved.
 *
 * @file: Ancestor.Base.js
 * @path: js-src/Ancestor/
 * @desc: Ancestor模块下基础业对象类
 * @author: lichuning@qiyi.com
 * @date: 2013-04-10
 */
///import js-src/lib/
///import js-src/com/

define('../entrance_record/Ancestor.Grid',['require','exports','module'],function (require, exports, module) {

    Ancestor.Grid = function (options) {
    };
    /**
     * 每个Action都设置一个初始化方法 用于初始化Ancestor 原型对象，默认不重复初始化
     *
     * @param {Boolean}
     *            force 是否强制初始化
     *
     */
    Ancestor.Grid.prototype = $.extend(true, {}, Com.Grid, {
        /**
         * 素材库查询方法
         * @param params 查询参数，采用jquery formSerialize
         * @param callback
         */
        query: function (callback) {

            var self = this;
            var $grid = self.$grid;

            var params = this.getParam();

            $grid.jqGrid('setGridParam', {
                postData: params
            }).trigger('reloadGrid', [
                {
                    page: 1
                }
            ]);

        },
        getParam: function () {

            var self = this;
            var $container = self.options.$container;
            var $grid = self.$grid;
            Com.Grid.overridePostData($grid);
            var params = {};
            var $elements = $.makeArray($container.find('form.query').prop('elements'));

            $.each($elements, function () {
                if (this.name) {
                    var key = $(this).attr('data-key');
                    if (key) {
                        params[this.name] = $(this).attr(key) || '';
                    } else {
                        params[this.name] = $(this).val();
                    }
                }
            });

            return params;
        },

        echoQuery: function () {
            var self = this;
            var $container = self.options.$container;

            this.query();

        },

        getGridConfig: function (table, tableColModel) {
            var self = this;
            var tableConfig = $.extend(true, {}, table || self.config.TABLE);
            var colModel = tableConfig.colModel;
            var newColModel = [];
            var colModelConfig = tableColModel || self.config.TABLE_COLMODEL_CONFIG;

            $.each(colModel, function (i, model) {
                newColModel.push(colModelConfig[model]);
            });
            tableConfig.colModel = newColModel;
            return tableConfig;
        },

        initGrid: function (options, callback) {
            var self = this;

            var gridConfig = self.getGridConfig();

            var $gridContainer = self.options.$container;

            var type = self.getType();
            var $pager = $gridContainer.find('div.pager');
            var $grid = $gridContainer.find('table.grid');
            var params = self.getParam();
            options = $.extend(true, {
                pager: $pager,
                mtype: 'post',

                postData: $.extend(true, {
                    type: type

                }, params),

                sortname: 'createTime',
                sortorder: 'desc',


                multiselect: true,

                multiselectWidth: 30

            }, gridConfig, options);

            $grid.jqGrid('scroll', {});
            $grid.jqGrid(options);

        },

        reload: function (params) {
            var type = this.getType();
            params = $.extend(true, {
                type: type
            }, params);
            this.$grid.jqGrid('setGridParam', {
                postData: params
            }).trigger('reloadGrid');
        }


    })
});


/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Ancestor.Dao.js
 * @path:   js-src/Ancestor/
 * @desc:   负责本模块的远程调用的静态对象
 * @author: jiegang@qiyi.com
 * @date:   2015-01-11
 */
define('../entrance_record/Ancestor.Config',['require','exports','module'],function(require, exports, module) {


    ///import js-src/lib/
    ///import js-src/com/
    window.GLOBAL =   window.GLOBAL || {};
    GLOBAL.user = {
        area: "sh"
    };
    GLOBAL.currentDate = Com.date.getCurrentDate();

    Ancestor.Config = (function() {
        var EPG_AUTH = {
            From: 'frontend', // 来源
            key: '7dpHGKMy4hAh3DmC' // 密钥
        };
        return {
            EPG_AUTH: EPG_AUTH
        };
    })();

});
/**
 * @file:   Ancestor.Util.js
 * @path:   js/Ancestor/
 * @desc:
 * @author: karkarrotxu@qiyi.com
 * @date:   2017-08-15
 */
define('../entrance_record/Ancestor.Util',['require','exports','module'],function (require, exports, module) {


    ///import js-src/lib/
    ///import js-src/com/
    window.Ancestor = window.Ancestor || {
        version: '1.0'
    };
    Ancestor.Util = (function () {
        // 组装 sign
        var authorization = function (options) {
            var rawSign = options.url + options.clientTime + Ancestor.Config.EPG_AUTH.key;
            return qui.md5("hashString", rawSign);
        };

        var getUrlId = function (name) {

            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null)
                return r[2];
            return null;
        };

        /**
         * 限制输入框中字符个数，一个汉字相当于两个字符，wordCount是最多允许的汉字个数
         * @param  {jquery  object}  $des  限制字符个数的输入框
         * @param  {Number}  wordCount     允许输入的最多汉字个数,默认为450个汉字
         * @param  {Boolean} isFilterChars 是否过滤输入内容，true过滤，false或undefined不过滤
         * @param  {Array}  filterChars    需要过滤的字符集，如['$','.']，意为全局过滤 $ *                                 和 .
         */
        var limitWordCount = function ($des, wordCount, isFilterChars, filterChars) {
            wordCount = wordCount || 450;
            var t = function (textarea) {
                var $textarea = $(textarea);
                var text = $textarea.val();
                if (isFilterChars) {
                    // text = Com.string.filterSpecialChars(text, filterChars);
                    $textarea.val(text);
                }
                var length = Com.string.getStrLength(text);
                if (length > wordCount * 2) {
                    $textarea.val(Com.string.substrCn(text, wordCount));
                }
                text = $textarea.val();
                length = Com.string.getStrLength(text);
                $textarea.parent().find('span.leftWordsCount').text(wordCount - Math.round(length / 2));
            };
            $des.bind({
                input: function () {
                    t(this);
                },
                propertychange: function () {
                    t(this);
                },
                keyup: function () {
                    t(this);
                }
            });
            $des.keyup();
        };
        var getAuth = function (str) {
            var auth = {
                    'sign': '',
                    'clientTime': '',
                    'from': ''
                },
                time = parseInt(new Date().getTime() / 1000);
            auth.from = Ancestor.Config.EPG_AUTH.From;
            auth.clientTime = time;
            auth.sign = qui.md5("hashString", str + time + Ancestor.Config.EPG_AUTH.key);
            return auth;

        };

        var buildHeader = function(){
            var node1 = $('<nav class="navbar navbar-default navbar-fixed-top" role="navigation"></nav>');
            var node2 = $('<div class="container-fluid"></div>')
            var node2_1 = $('<div class="navbar-header"></div>');
            var node2_1_1 = $('<a class="navbar-brand" href="http://lego.iqiyi.com">LEGO</a>');
            var node2_2 = $('<div class="collapse navbar-collapse"></div>');
            node2_1_1.appendTo(node2_1);
            node2_1.appendTo(node2);
            node2_2.appendTo(node2);
            node2.appendTo(node1);
            node1.appendTo($("header.main-header"));
        }


        var buildMenu = function (usrData) {
            var parent = $("header div.navbar-collapse")
            var node5 = $('<ul class="nav navbar-nav j-lego-nav"></ul>');
            var node6 = $('<li class="dropdown "></li>');
            var node6_1 = $('<a href="javascript:;" class="dropdown-toggle">直播中心 <span class="caret"></span></a>');
            var node6_2 = $('<ul class="dropdown-menu dropdown-sub-nav" role="menu" data-cid="live"></ul>');
            var navListData = [];
            $.each(usrData, function (i, element) {
                navListData.push('<li class="navbar-sub-nav">');
                navListData.push(' <div class="navbar-sub-title"><span class="glyphicon glyphicon-th-large"></span>' + element.name + '</div>');
                navListData.push('<ul class="navbar-sub-list list-inline">');
                $.each(element.items, function (j, child) {
                    navListData.push('<li><a href="' + child.url + '" target="_blank">' + child.name + '</a></li>');
                })
                navListData.push('</ul>');
                navListData.push('</li>');
            })
            $(navListData.join("")).appendTo(node6_2);
            node6_1.appendTo(node6);
            node6_2.appendTo(node6);
            node6.appendTo(node5);
            node5.appendTo(parent);
        }
        var buildUserInfo = function (usrData) {
            var parent = $("header div.navbar-collapse")
            var htmlArr = [];
            htmlArr.push('  <ul class="nav navbar-nav navbar-right">');
            htmlArr.push('    <li class="dropdown" style="right: 30px">');
            htmlArr.push('         <a href="#" class="dropdown-toggle" data-toggle="dropdown" aria-expanded="true"><span class="glyphicon glyphicon-user"></span>' + usrData.authInfo.userName + '</a>');
            htmlArr.push('        <ul class="dropdown-menu dropdown-user-info" role="menu"> ');
            htmlArr.push('            <li class="user-header"> ');
            htmlArr.push('               <p>' + usrData.authInfo.userName + '</p> ');
            htmlArr.push('                 <p><small>UID: ' + usrData.authInfo.uid + '</small></p> ');
            htmlArr.push('          </li>');
            htmlArr.push('           <li class="user-footer clearfix">');
            htmlArr.push('              <div class="text-center">');
            htmlArr.push(' <a href="'+usrData.loginOut+'" class="btn btn-default btn-block" data-ripple-color="#444">退出</a>');
            htmlArr.push('  </div></li></ul></li></ul>');
            parent.append(htmlArr.join(""));
        }

        var buildFooter = function (epg_version) {
            var htmlArr = [];
            htmlArr.push(' <footer class="main-footer">')
            htmlArr.push('   <div class="scroll-to-top scroll-to-top-hide" id="BackToTopButton">')
            htmlArr.push('     <a class="btn" href="javascript:;"><i class="glyphicon glyphicon-circle-arrow-up"></i>返回顶部</a>')
            htmlArr.push('  </div>')
            htmlArr.push('    <div class="container">')
            htmlArr.push('        <div class="footer-content">')
            htmlArr.push('           <p class="text-center">' + epg_version + ' Copyright © 2018 <a href="//www.iqiyi.com">iQIYI.COM</a> All rights reserved.</p>')
            htmlArr.push('           <p class="text-center">请使用 Chrome，Firefox，IE10+ 等浏览器访问本站</p>')
            htmlArr.push('       </div>')
            htmlArr.push('    </div>')
            htmlArr.push('  </footer>');
            $("body").append(htmlArr.join(""));
        }

        return {
            authorization: authorization,
            getUrlId: getUrlId,
            limitWordCount: limitWordCount,
            getAuth: getAuth,
            buildMenu: buildMenu,
            buildUserInfo: buildUserInfo,
            buildFooter: buildFooter,
            buildHeader:buildHeader
        };
    })();

});
/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Ancestor.Dao.js
 * @path:   js-src/Ancestor/
 * @desc:   负责本模块的远程调用的静态对象
 * @author: jiegang@qiyi.com
 * @date:   2015-01-12
 */
define(
    '../entrance_record/Ancestor.Dao',['require','exports','module'],function(require, exports, module) {

        Ancestor.Dao = (function() {
            var ajax = function(options, authPath) {
                if (authPath)
                    $.ajax($.extend(options, {
                        beforeSend: function(request) {
                            var authBase = Ancestor.Util.getAuth(authPath);
                            request.setRequestHeader('Sign', authBase.sign);
                            request.setRequestHeader("Time", authBase.clientTime);
                            request.setRequestHeader("From", authBase.from);
                            request.setRequestHeader("UserName", (auth.baseInfo.authInfo==null) ? "" : escape(auth.baseInfo.authInfo.userName).toLocaleLowerCase().replace(/%u/gi, '\\u'));
                        }
                    }));
                else
                    $.ajax(options);
            };

            // XMLHttp Request
            var _getXHR = function() {
                return new XMLHttpRequest() || new ActiveXObject('Msxml2.XMLHTTP') || new ActiveXObject('Microsoft.XMLHTTP');
            };

            var redirectRequest = function(options, callback) {
                var options = {
                    url: '/api/redirect',
                    dataType: 'json',
                    data: options,
                    method: 'post',
                    beforeSend: function(request) {
                        var auth = Ancestor.Util.getAuth('/redirect');
                        request.setRequestHeader('Sign', auth.sign);
                        request.setRequestHeader("Time", auth.clientTime);
                        request.setRequestHeader("From", auth.from);
                    },
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                ajax(options, "/redirect");
            };

            return {
                redirectRequest: redirectRequest,
                ajax: ajax
            };
        })();
    }
);

define(
    '../epg2/EpgWeb',['require','exports','module'],function(require, exports, module) {
        window.EpgWeb = window.EpgWeb || {
            version: '1.0'
        };

        EpgWeb.Constant = {
            //baseApiUrl:"http://test.admin.epg.qiyi.domain/api/",
            baseApiUrl: "/api/",
            thirdUrl_audit_people: "http://lego.iqiyi.com/suggest/audit-people",
            originalUrl: "http://10.23.84.18:8500/",
            third_location_url:"http://lego.iqiyi.com/suggest/region",
            thirdUrl_qitan_url: "http://api.t.iqiyi.com/qx_api/resource/get_id_by_name",
            thirdUrl_add_qitan_url: "http://api.t.iqiyi.com/qx_api/resource/add_resource",
            thirdUrl_video_url: "http://lego.iqiyi.com/suggest/simple-video",
            thirdUrl_album_url: "http://lego.iqiyi.com/suggest/album",
            thirdUrl_playlist_url: "http://lego.iqiyi.com/suggest/playlist",
            thirdUrl_channel_url:"http://lego.iqiyi.com/apis/channel/list",
            thirdUrl_video_area_url: "http://lego.iqiyi.com/suggest/simple-video-area",
            thirdUrl_album_area_url: "http://lego.iqiyi.com/suggest/album-area",
            thirdUrl_apis_search_area_url: "http://lego.iqiyi.com/apis/search/search-area",
            thirdUrl_category_first_list_url:"http://lego.iqiyi.com/apis/category/live-first-list",
            // use for child secLv thirdLv
            thirdUrl_category_child_list_url: "http://lego.iqiyi.com/category/list",
            thirdUrl_passport_url:"http://passport.qiyi.domain/apis/internal/user_info.action",
            devMode: auth.dev()
        }
        EpgWeb.urlConfig = (function () {
            var useUrl = EpgWeb.Constant.baseApiUrl;
            var programListUrl = useUrl + "program/list";
            var programListSortUrl = useUrl + "program/listSort";
            var programAddUrl = useUrl + "program/add";
            var programDelUrl = useUrl + "program/delete";
            var programEditUrl = useUrl + "program/edit";
            var programLogUrl = useUrl + "program/loglist";
            var configsUrl = useUrl + "configs";
            var channelListUrl = useUrl + "channel/list";
            var programSyncUrl = useUrl + "program/syncTVMao";
            var redirectUrl = useUrl + "redirect";
            var channelGetUrl = useUrl + "channel/get";
            var queryPuYuUrl = useUrl + "program/queryPuYu";
            var carouselRuleListUrl = useUrl + "carousel/get";
            var carouselRuleDelUrl = useUrl + "carousel/del";
            var carouselRuldAddUrl = useUrl + "carousel/create";
            var programLiveQueryUrl = useUrl + "program/liveQuery";
            var programMoveUrl = useUrl + "program/move";
            var programToggleLockUrl = useUrl + "program/toggleLock";
            var programBatchAddUrl = useUrl + "program/batchAdd";
            var carouselEpisodeBatchAddUrl = useUrl + "carousel/carouselEpisode/batchAdd";
            var carouselEpisodeBatchDelUrl= useUrl + "carousel/carouselEpisode/batchDel";
            var carouselEpisodeListUrl= useUrl + "carousel/carouselEpisode/list";
            var carouselEpisodeIndexMoveUrl= useUrl + "carousel/carouselEpisode/indexMove";
            var carouselEpisodeIndexMoveByIndexUrl= useUrl + "carousel/carouselEpisode/indexMove/byIndex";
            var programDaySortUrl = useUrl + "program/daySort";
            var programIndexMoveUrl = useUrl + "program/indexMove";
            var programBatchDelUrl = useUrl + "program/batchDel";
            var platSettingsGetUrl = useUrl + "channel/getPlatSettings";
            var yesterdayEndTimeUrl = useUrl + "program/yesterdayEndTime";
            var automationAddUrl = useUrl + "carousel/automation/add";
            var automationDelUrl = useUrl + "carousel/automation/del";
            var automationListUrl = useUrl + "carousel/automations";
            var automationMoveUrl = useUrl + "carousel/automation/indexMove";
            var automationMoveByIndexUrl = useUrl + "carousel/automation/indexMove/byIndex";
            var automationChangeStatusUrl = useUrl + "carousel/automation/changeStatus";
            var getBroadcastControlsUrl = useUrl+"broadcast/controls";
            var reservation_create_Url = useUrl+ "reservation";
            var reservation_del_Url = useUrl+ "reservation/del";
            var reservation_edit_Url = useUrl+"reservation/edit";
            var reservation_get_Url = useUrl+ "reservations";
            var setBroadcastControlAllUrl= useUrl+"broadcast/controlall";
            var setBroadcastControlUrl  = useUrl+"broadcast/control";
            var platSettingsSaveUrl =  useUrl+"channel/savePlatSettings";
            var programBroadcastControlUrl =  useUrl+"program/broadcast/control";
            var programForceCheckUrl = useUrl + "program/forceCheck";
            var advertModifyUrl  = useUrl + "advert/modify";
            var directorCreateUrl =  useUrl + "director/create";
            var notifyAlertUrl = useUrl + "notify/alertPlatform";
            function getQiPuBaseUrl(qipuId){
                var plusUrl = EpgWeb.Constant.devMode ? "http://qipu-test.qiyi.domain/int/entity/nocache/@.json" : "http://qipu.qiyi.domain/int/entity/nocache/@.json";
                return plusUrl.replace("@", "" + qipuId);
            }
            return {
                programList: programListUrl,
                programListSortUrl: programListSortUrl,
                programAdd: programAddUrl,
                programDel: programDelUrl,
                programEdit: programEditUrl,
                programLog:programLogUrl,
                programForceCheck:programForceCheckUrl,
                configs: configsUrl,
                channelList: channelListUrl,
                channelGet: channelGetUrl,
                programSyncUrl: programSyncUrl,
                queryPuYu: queryPuYuUrl,
                carouselRuleListUrl: carouselRuleListUrl,
                carouselRuleDelUrl: carouselRuleDelUrl,
                carouselRuldAddUrl: carouselRuldAddUrl,
                carouselEpisodeBatchAddUrl:carouselEpisodeBatchAddUrl,
                carouselEpisodeBatchDelUrl:carouselEpisodeBatchDelUrl,
                carouselEpisodeListUrl:carouselEpisodeListUrl,
                carouselEpisodeIndexMoveUrl:carouselEpisodeIndexMoveUrl,
                carouselEpisodeIndexMoveByIndexUrl:carouselEpisodeIndexMoveByIndexUrl,
                programLiveQueryUrl: programLiveQueryUrl,
                programMoveUrl: programMoveUrl,
                programToggleLockUrl: programToggleLockUrl,
                programDaySortUrl: programDaySortUrl,
                programBatchAddUrl: programBatchAddUrl,
                programIndexMoveUrl: programIndexMoveUrl,
                programBatchDelUrl: programBatchDelUrl,
                platSettingsGetUrl: platSettingsGetUrl,
                yesterdayEndTimeUrl: yesterdayEndTimeUrl,
                automationAddUrl: automationAddUrl,
                automationDelUrl: automationDelUrl,
                automationListUrl: automationListUrl,
                automationMoveUrl: automationMoveUrl,
                automationChangeStatusUrl: automationChangeStatusUrl,
                reservationCreate:reservation_create_Url,
                reservationDel:reservation_del_Url,
                reservationGet:reservation_get_Url,
                getBroadcastControls:getBroadcastControlsUrl,
                reservationEdit:reservation_edit_Url,
                setBroadcastControlAllUrl:setBroadcastControlAllUrl,
                setBroadcastControl:setBroadcastControlUrl,
                platSettingsSaveUrl:platSettingsSaveUrl,
                programBroadcastControlUrl:programBroadcastControlUrl,
                redirect: redirectUrl,
                advertModifyUrl:advertModifyUrl,
                directorCreateUrl:directorCreateUrl,
                notifyAlertUrl:notifyAlertUrl,
                getQiPuBaseUrl:getQiPuBaseUrl
            }
        })();

        EpgWeb.ajaxQueue = (function () {
            var entity = this;
            var taskArr = [];
            var batchArr = [];
            var timerId = -1;
            var errorCollectArr = [];
            var afterCompleteArr = [];
            var status = -2;
            var checkComplete = function () {
                switch (status) {
                    case 1:
                        clearInterval(timerId);
                        timerId = -1
                        if (errorCollectArr.length > 0) {
                            var totalError = errorCollectArr.join("\n");
                            errorCollectArr = [];
                            EpgWeb.Plugin.showTips({
                                content: totalError,
                                type: "error"
                            })
                        }
                        status = 2;
                        loadComplete();
                        batchComplete();
                        break;
                    case -1:
                        $.each(taskArr, function (index, obj) {
                            if (obj.responseData == null) {
                                var ajaxData = obj.ajaxData;
                                $.ajax({
                                    type: ajaxData.type,
                                    url: ajaxData.url,
                                    dataType: ajaxData.dataType,
                                    beforeSend: function (request) {
                                        request.setRequestHeader("Sign", "#f93Uc31K24()_@");
                                    },
                                    data: ajaxData.data,
                                    success: function (data) {
                                        var tempTarget = findTaskByRegName(obj.regName);
                                        if (tempTarget.needRemove == true) {
                                            removeTask(obj.regName);
                                        } else {
                                            tempTarget.responseData = data;
                                        }
                                        if (ajaxData.success != null) {
                                            ajaxData.success(data);
                                        }
                                    },
                                    error: function (data) {
                                        if (ajaxData.error != null) {
                                            ajaxData.error(data);
                                        }
                                        errorCollectArr.push(obj.regName + " 请求失败")
                                        removeTask(obj.regName)
                                    }
                                });
                            }
                        })
                        status = 0;
                        timerId = setInterval(checkComplete, 16);
                        break;
                    case 0:
                        var allComplete = true;
                        $.each(taskArr, function (index, obj) {
                            if (obj.responseData == null) {
                                allComplete = false;
                                return true;
                            }
                        });
                        if (allComplete) {
                            status = 1;
                        }
                        break;
                }
            }

            var batchComplete = function () {
                var tempArr = batchArr;
                batchArr =[];
                while (tempArr.length > 0) {
                    var batchRequestData = tempArr.pop();
                    batchRequestData.handler({"originalArr": batchRequestData.originalArr,
                            "acceptArr": batchRequestData.acceptMsgArr}
                    );
                }
            }

            var loadComplete = function () {
                console.log("loadComplete over");
                var tempArr = afterCompleteArr;
                afterCompleteArr = [];
                while (tempArr.length > 0) {
                    var excuteFunc = tempArr.shift();
                    excuteFunc.call();
                }
            }

            var push = function (regName, ajaxData, responseData, needRemove){
                if (typeof(needRemove) != "boolean") {
                    needRemove = needRemove == null ? false : true
                }
                taskArr.push({"regName": regName, "ajaxData": ajaxData, "responseData": responseData, "needRemove": needRemove})
            }

            var batchRequest = function (regName, ajaxData, sendDataArr, handler){
                var acceptMsgArr = [];
                var batchRequestData = {"originalArr": sendDataArr, "acceptMsgArr": acceptMsgArr, handler: handler }
                batchArr.push(batchRequestData)
                $.each(sendDataArr, function (index, obj) {
                    taskArr.push(
                        {
                            "regName": regName + "_" + index,
                            "ajaxData": {
                                type: ajaxData.type,
                                url: ajaxData.url,
                                dataType: ajaxData.dataType,
                                data: obj,
                                success: function (data) {
                                    var formatData = null;
                                    if (data != null) {
                                        formatData = {"nodeIndex": index, "operationSuccess": false, "responseData": data, "msg": data.msg};
                                        if (data.code == "A00000") {
                                            formatData.operationSuccess = true;
                                        }
                                    } else {
                                        formatData = {"nodeIndex": index, "error": true, "operationSuccess": false, "responseData": data};
                                    }
                                    acceptMsgArr.push(formatData)
                                },
                                error: function (data) {
                                    var formatData = {"nodeIndex": index, "error": true, "operationSuccess": false, "responseData": data};
                                    acceptMsgArr.push(formatData);
                                }
                            },
                            "needRemove": true
                        });
                })
            }

            var startLoad = function(){
                if (status != -2 && status != 2) {
                    return false;
                }
                status = -1;
                console.log(JSON.stringify(taskArr) );
                checkComplete();
                return true;
            }

            var findResponseData = function (regName) {
                var task = findTaskByRegName(regName);
                if (task == null) {
                    return null;
                }
                return task.responseData;
            }
            var removeTask = function (regName) {
                var task = findTaskByRegName(regName);
                if (task != null) {
                    var taskIndex = taskArr.indexOf(task)
                    taskArr.splice(taskIndex, 1);
                }
            }

            var findTaskByRegName = function(regName) {
                if (taskArr.length == 0) {
                    return null;
                }
                var returnTarget = null;
                $.each(taskArr, function (index, obj) {
                    if (obj.regName == regName) {
                        returnTarget = obj;
                        return false;
                    }
                })
                return returnTarget;
            }

            var afterLoadComplete = function (callback) {
                if (typeof(callback) == "function") {
                    afterCompleteArr.push(callback);
                }
            }

            var isRunning = function () {
                return status == 0;
            }

            function getTaskArr(){
                return [].concat(taskArr);
            }

            function getStatus(){
                return status;
            }

            return {
                startLoad:startLoad,
                findResponseData:findResponseData,
                findTaskByRegName:findTaskByRegName,
                batchRequest:batchRequest,
                push:push,
                isRunning:isRunning,
                removeTask:removeTask,
                afterLoadComplete:afterLoadComplete,
                getTaskArr:getTaskArr,
                getStatus:getStatus
            }
        })();
    }
);
define(
    '../epg2/EpgWeb.Util',['require','exports','module'],function (require, exports, module) {
        EpgWeb.Util = $.extend(true, {}, Ancestor.Util, {
            tranDurationFormat: function (duration) {
                var darArr = [];
                darArr.push(duration % 60);
                duration = ( duration - duration % 60) / 60;
                if (duration > 0) {
                    darArr.push(duration % 60);
                }
                duration = ( duration - duration % 60) / 60;
                if (duration > 0) {
                    darArr.push(duration % 24);
                }
                duration = ( duration - duration % 24) / 24;
                if (duration > 0) {
                    darArr.push(duration);
                }
                var retValue = "";
                switch (darArr.length) {
                    case 4:
                        retValue = darArr[3] + "天";
                    case 3:
                        retValue += darArr[2] + "时";
                    case 2:
                        retValue += darArr[1] + "分";
                    case 1:
                        retValue += darArr[0] + "秒";
                        break;
                }
                return retValue;
            },
            makeUpRedirect: function (url, method, params, needCookie) {
                var requestData = {url: url, type: method, params: params};
                if (needCookie === true) {
                    requestData.needCookie = true;
                }
                return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
            },
            quickDateFormat: function (startTime) {
                return startTime.getFullYear() + "-" +
                    (startTime.getMonth() < 9 ? "0" + (startTime.getMonth() + 1) : (startTime.getMonth() + 1) ) + "-" +
                    (startTime.getDate() < 10 ? "0" + startTime.getDate() : startTime.getDate() );
            },
            bindDateMax: function (name1, name2, plusData) {
                $("input[name=" + name1 + "]").datetimepicker({
                    sliderAccessArgs: { touchonly: false },
                    onClose: function (selectedDate) {
                        $("input[name=" + name2 + "]").datetimepicker("option", "maxDate", selectedDate);
                        var toDate = new Date(selectedDate.replace(/-/g, "/"))
                        $("input[name=" + name2 + "]").datetimepicker("option", "maxDateTime", toDate);
                    }
                })
                if (plusData != null) {
                    $("input[name=" + name1 + "]").datetimepicker("option", "minDate", plusData.minDate);
                    $("input[name=" + name1 + "]").datetimepicker("option", "minDateTime", plusData.minDateTime);
                }
            },
            setZeroTime: function (checkTime) {
                checkTime.setSeconds(0);
                checkTime.setMinutes(0);
                checkTime.setHours(0);
                checkTime.setMilliseconds(0);
            },
            setDayLastTime: function (checkTime) {
                checkTime.setSeconds(59);
                checkTime.setMinutes(59);
                checkTime.setHours(23);
                checkTime.setMilliseconds(0);
            },

            bindDate: function (nameMin, nameMax, plusData) {
                var options1 = {
                    sliderAccessArgs: { touchonly: false },
                    onClose: function (selectedDate) {
                        console.log("bindDate " +  selectedDate )
                        $("input[name=" + nameMax + "]").datetimepicker("option", "minDate", selectedDate);
                        var toDate = new Date(selectedDate.replace(/-/g, "/"))
                        $("input[name=" + nameMax + "]").datetimepicker("option", "minDateTime", toDate);
                    }
                }
                var options2 = {
                    sliderAccessArgs: { touchonly: false },
                    onClose: function (selectedDate) {
                        console.log("bindDate " +  selectedDate )
                        $("input[name=" + nameMin + "]").datetimepicker("option", "maxDate", selectedDate);
                        var toDate = new Date(selectedDate.replace(/-/g, "/"))
                        $("input[name=" + nameMin + "]").datetimepicker("option", "maxDateTime", toDate);
                    }
                }
                if (plusData != null && plusData.hasOwnProperty("slider")) {
                    options1.controlType = "slider";
                    options2.controlType = "slider";
                }
                $("input[name=" + nameMin + "]").datetimepicker(options1)
                $("input[name=" + nameMax + "]").datetimepicker(options2)
                if (plusData != null) {
                    $("input[name=" + nameMin + "]").datetimepicker("option", "maxDate", plusData.maxDate);
                    $("input[name=" + nameMin + "]").datetimepicker("option", "maxDateTime", plusData.maxDateTime);
                    $("input[name=" + nameMax + "]").datetimepicker("option", "minDate", plusData.minDate);
                    $("input[name=" + nameMax + "]").datetimepicker("option", "minDateTime", plusData.minDateTime);
                }
            },



            bindDateMin: function (name1, name2, plusData) {
                $("input[name=" + name1 + "]").datetimepicker({
                    sliderAccessArgs: { touchonly: false },
                    onClose: function (selectedDate) {
                        $("input[name=" + name2 + "]").datetimepicker("option", "minDate", selectedDate);
                        var toDate = new Date(selectedDate.replace(/-/g, "/"))
                        $("input[name=" + name2 + "]").datetimepicker("option", "minDateTime", toDate);
                    }
                })
                if (plusData != null) {
                    $("input[name=" + name1 + "]").datetimepicker("option", "maxDate", plusData.maxDate);
                    $("input[name=" + name1 + "]").datetimepicker("option", "maxDateTime", plusData.maxDateTime);
                }
            },
            createPageBean: function () {
                return (function () {
                    var source = [];
                    var dataLength = source.length;
                    var rowNum = 10;
                    var total = (dataLength % rowNum == 0 ? 0 : 1) + parseInt(dataLength / rowNum);
                    var cur = 1;

                    function goToFirst() {
                        return goToUser(1);
                    }

                    function goToLast() {
                        return goToUser(total);
                    }

                    function goToUser(toPage) {
                        if (toPage < 1) toPage = 1;
                        if (toPage > total) toPage = total;
                        cur = toPage;
                        var end = cur * rowNum > dataLength ? dataLength : cur * rowNum;
                        var showData = source.slice((cur - 1) * rowNum, end);
                        return {"total": total, "page": cur, "records": dataLength, "rows": showData};
                    }

                    function getCur() {
                        return goToUser(cur);
                    }

                    function goNext() {
                        return goToUser(cur + 1);
                    }

                    function goPrev() {
                        return goToUser(cur - 1);
                    }

                    function setNewData(newData, newRowNum) {
                        source = newData == null ? [] : newData;
                        if (newRowNum != null && newRowNum > 0) {
                            rowNum = newRowNum;
                        }
                        dataLength = source.length;
                        total = (dataLength % rowNum == 0 ? 0 : 1) + parseInt(dataLength / rowNum);
                    }

                    function addNewOne(newOne) {
                        source.push(newOne);
                        setNewData(source, rowNum);
                    }

                    function delOne(delOne) {
                        var targetIndex = source.indexOf(delOne);
                        if (targetIndex > -1) {
                            source.splice(targetIndex, 1);
                            setNewData(source, rowNum);
                        }
                    }

                    function getSource() {
                        return [].concat(source);
                    }

                    function findData(keyName, value) {
                        var ret = null;
                        if (value == null || keyName == null) {
                            return null;
                        }
                        $.each(source, function (i, element) {
                            if (element != null && element[keyName] == value) {
                                ret = element;
                                return true;
                            }
                        })
                        return ret;
                    }

                    function sortData(func) {
                        if (typeof( func ) == "function") {
                            source.sort(func);
                        }
                    }

                    return {
                        goToFirst: goToFirst,
                        goToLast: goToLast,
                        goToUser: goToUser,
                        goNext: goNext,
                        goPrev: goPrev,
                        getCur: getCur,
                        setNewData: setNewData,
                        addNewOne: addNewOne,
                        delOne: delOne,
                        getSource: getSource,
                        findData: findData,
                        sortData: sortData
                    }
                })()
            },
            pageBeanPageHandler: function (gridId, pageId, pageBean, pgButton) {
                var retValue = null;
                switch (pgButton) {
                    case "next_" + pageId:
                        retValue = pageBean.goNext()
                        break;
                    case "prev_" + pageId:
                        retValue = pageBean.goPrev()
                        break;
                    case "last_" + pageId:
                        retValue = pageBean.goToLast()
                        break;
                    case "user":
                        retValue = pageBean.goToUser(parseInt($("#gbox_" + gridId + " .ui-pg-input").val()));
                        break;
                    case "first_" + pageId:
                        retValue = pageBean.goToFirst();
                        break;
                }
                return retValue
            },
            transGetParams: function (params) {
                var str = "";
                for (var key in params) {
                    str += key + "=" + params[key] + "&";
                }
                if (str.length > 0) {
                    str = str.substr(0, str.length - 1);
                }
                return str;
            },

            formatDateTimeFormat: function (myDate) {
                var year = myDate.getFullYear();
                var month = ("0" + (myDate.getMonth() + 1)).slice(-2);
                var day = ("0" + myDate.getDate()).slice(-2);
                var h = ("0" + myDate.getHours()).slice(-2);
                var m = ("0" + myDate.getMinutes()).slice(-2);
                var s = ("0" + myDate.getSeconds()).slice(-2);
                return year + "-" + month + "-" + day + " " + h + ":" + m + ":" + s;
            },
            getQueryComponent: function (handlerObj) {
                return {
                    source: null,
                    total: 0,
                    completeNum: 0,
                    handlerObj: handlerObj,
                    doInit: function (newArr) {
                        var self = this;
                        self.source = newArr;
                        self.total = newArr.length;
                        self.completeNum = 0;
                        self.doSubmit();
                    },
                    doSubmit: function () {
                        var self = this;
                        self.doBefore();
                        $.each(self.source, function (i, element) {
                            self.doSingle(element, function () {
                                self.notifyHandler()
                            });
                        })
                    },
                    doBefore: function () {
                        var self = this;
                        if (self.handlerObj != null) {
                            if (self.handlerObj.hasOwnProperty("doBefore")) {
                                self.handlerObj.doBefore();
                            }
                        }
                    },
                    doAfter: function () {
                        var self = this;
                        if (self.handlerObj != null) {
                            if (self.handlerObj.hasOwnProperty("doAfter")) {
                                self.handlerObj.doAfter();
                            }
                        }
                    },
                    doSingle: function (element, notifyHandler) {
                        var self = this;
                        if (self.handlerObj != null) {
                            if (self.handlerObj.hasOwnProperty("doSingle")) {
                                self.handlerObj.doSingle(element, notifyHandler);
                            }
                        }
                    },
                    notifyHandler: function () {
                        var self = this;
                        self.completeNum++;
                        if (self.completeNum == self.total) {
                            self.doAfter();
                        }
                    }
                };
            },
            createWeekManager: function (labelArr) {
                return (function ($labelArr) {
                    var focusStartTime = null;
                    var selectDateTime = null;
                    var weekday = "星期日,星期一,星期二,星期三,星期四,星期五,星期六".split(",");

                    function preWeek() {
                        if (focusStartTime != null) {
                            updateWeek(new Date(focusStartTime.getTime() - 7 * 86400 * 1000));
                        }
                    }

                    function nextWeek() {
                        if (focusStartTime != null) {
                            updateWeek(new Date(focusStartTime.getTime() + 7 * 86400 * 1000));
                        }
                    }

                    function updateWeek(startTime) {
                        if (startTime != null) {
                            focusStartTime = startTime;
                        }
                        var tempStartTime = new Date(focusStartTime.getTime());
                        $labelArr.each(function (i, element) {
                            var lDateFormat = EpgWeb.Util.quickDateFormat(tempStartTime);
                            $(element).attr("query-date", lDateFormat);
                            $(element).removeClass("selected");
                            $(element).html(weekday[tempStartTime.getDay()] + "<br>" + lDateFormat);
                            if (lDateFormat == selectDateTime) {
                                $(element).addClass("selected");
                            }
                            tempStartTime.setTime(tempStartTime.getTime() + 86400 * 1000);
                        })
                    }

                    function quickToCurrentWeek() {
                        var current = new Date();
                        var currentIndex = -1;
                        if (current.getDay() == 0) {
                            currentIndex = 6;
                        } else {
                            currentIndex = current.getDay() - 1;
                        }
                        selectDateTime = EpgWeb.Util.quickDateFormat(current)
                        updateWeek(new Date(current.getTime() - currentIndex * 86400 * 1000));
                        //updateTableByDate(selectDateTime);
                        return selectDateTime;
                    }

                    return{
                        preWeek: preWeek,
                        nextWeek: nextWeek,
                        quickToCurrentWeek: quickToCurrentWeek
                    }
                })(labelArr)
            },
            createHeartBeatUtil: function () {
                return  (function () {
                    var params = {
                        startTime: 0,
                        isStarted: false,
                        indexId: 0,
                        dataArr: []
                    }

                    function doHeartBeat() {
                        var curTime = Date.now();
                        var cpArr = [].concat(params.dataArr);

                        $.each(cpArr, function (i, element) {
                            tick(element, curTime);
                        })
                    }

                    function start() {
                        if (params.isStarted) {
                            console.log("has started");
                            return;
                        }
                        params.startTime = Date.now();
                        params.isStarted = true;
                        $.each(params.dataArr, function (i, elment) {
                            elment.lastTime = params.startTime;
                        })
                        setInterval(function () {
                            doHeartBeat();
                        }, 160)
                    }

                    function tick(element, curTime) {
                        if (element.block || element.stop) {
                            return;
                        }
                        if (element.lastTime + element.gapTime < curTime) {
                            element.lastTime = curTime;
                            element.options.handler();
                            if (element.options.needBlock) {
                                element.block = true;
                            }
                        }
                    }

                    function pushTask(taskObj) {
                        params.indexId++;
                        var taskOptions = {
                            block: false,
                            stop: taskObj.stop || false,
                            options: taskObj,
                            id: params.indexId,
                            lastTime: 0
                        }
                        taskOptions.gapTime = accountGapTime(taskObj)
                        if (params.isStarted) {
                            taskOptions.lastTime = Date.now() + 100;
                        }
                        params.dataArr.push(taskOptions);
                        return taskOptions;
                    }

                    function accountGapTime(taskObj) {
                        var time = [0, 0, 0, 0];//ms,s,m,h
                        if ("ms" in taskObj.gap) {
                            time[0] = taskObj.gap.ms;
                        }
                        if ("s" in taskObj.gap) {
                            time[1] = taskObj.gap.s;
                        }
                        if ("m" in taskObj.gap) {
                            time[2] = taskObj.gap.m;
                        }
                        if ("h" in taskObj.gap) {
                            time[3] = taskObj.gap.h;
                        }
                        return  time[0] + time[1] * 1000 + time[2] * 60000 + time[3] * 3600000;
                    }

                    return {
                        start: start,
                        doHeartBeat: doHeartBeat,
                        pushTask: pushTask,
                        tick: tick
                    }
                })();
            },
            notifyAlert: function (sendData, handler) {
                EpgWeb.Dao.notifyAlert(sendData, function (rdata) {
                    handler(rdata)
                });
            },
            getCurrentUserEntity:function(){
                var ret = null;
                try{
                    ret =auth.baseInfo.authInfo;
                }catch (e){
                    console.warn(e);
                }
                return ret
            }
        });
    }
);
define(
    '../epg2/EpgWeb.Plugin',['require','exports','module'],function (require, exports, module) {
        EpgWeb.Plugin = {
            showTips: function (options) {
                if (!options.hasOwnProperty("type")) {
                    options.type = "success";
                }
                if ($(document).tips != null) {
                    $(document).tips(options)
                }
                if ($(document).tip != null) {
                    $(document).tip(options)
                } else {
                    console.log("no tips plugin " + options);
                }
            },
            Validate: (function () {
                var reg1 = /^\d+$/;
                var reg3 = /^[1-9]\d*$/;
                var reg2 = /^(19|20)\d{2}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1]) ([0-2][0-9]):([0-5][0-9]):([0-5][0-9])$/;
                var reg4 = /^([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/;
//                var _defaultHandler = function(msg){
//                    EpgWeb.Plugin.showTips({type: "error", content: msg})
//                }
                var _bindHandler = null;
                var checkObj = {
                    self_design: function (checkData, checkValue) {
                        return checkData.checkCall(checkData, checkValue)
                    },
                    date: function (checkData, checkValue) {
                        return checkDateFormat(checkValue);
                    },
                    not_empty: function (checkData, checkValue) {
                        return checkValue != null && $.trim(checkValue).length > 0;
                    },
                    eq: function (checkData, checkValue) {
                        return checkValue === checkData.other;
                    },
                    ne: function (checkData, checkValue) {
                        return checkValue !== checkData.other;
                    },
                    ge: function (checkData, checkValue) {
                        return  checkValue >= checkData.other;
                    },
                    gt: function (checkData, checkValue) {
                        return  checkValue > checkData.other;
                    },
                    lt: function (checkData, checkValue) {
                        return checkValue < checkData.other;
                    },
                    le: function (checkData, checkValue) {
                        return checkValue <= checkData.other;
                    },
                    positive:function(checkData, checkValue) {
                        return  checkPositive(checkValue)
                    },
                    number: function (checkData, checkValue) {
                        return checkNum(checkValue);
                    },
                    endsWith: function (checkData, checkValue) {
                        return checkValue != null && typeof(checkValue) == "string" && checkValue.slice(-(checkData.other.length)) == checkData.other;
                    }
                }

                function checkNum(checkString) {
                    return reg1.test(checkString)
                }

                function checkDateFormat(checkString) {
                    return reg2.test(checkString)
                }

                function checkPositive(checkString) {
                    return reg3.test(checkString)
                }

                function defaultHandler(msg) {
                    if(_bindHandler != null){
                        _bindHandler(msg);
                    }
                }

                function batchCheck(checkArr) {
                    if (checkArr == null) {
                        checkArr = [];
                    }
                    if (checkArr.length == 0) {
                        return true;
                    }
                    var flag = false;
                    $.each(checkArr, function (index, checkData) {
                        flag = baseCheck(checkData);
                        if (!flag) {
                            return false;
                        }
                    })
                    return flag;
                }

                function baseCheck(checkData) {
                    var flag = false;
                    //$.isArray(checkData.value )
                    if (!(checkData.value instanceof Array)) {
                        checkData.value = [checkData.value];
                    }
                    //$.isArray(checkData.error )
                    if (!(checkData.error instanceof Array)) {
                        checkData.error = [checkData.error];
                    }
                    if (checkData.handler == null) {
                        checkData.handler = defaultHandler;
                    }
                    $.each(checkData.value, function (index, checkValue) {
                        if (checkObj.hasOwnProperty(checkData.type)) {
                            flag = checkObj[checkData.type](checkData, checkValue);
                        }
                        if (!flag) {
                            var hint = checkData.error.length == checkData.value.length ? checkData.error[index] : checkData.error[0];
                            checkData.handler(hint);
                            return false;
                        }
                    })
                    return flag
                }
                function bindDefaultHandler(func){
                    _bindHandler = func;
                }
                return {
                    baseCheck: baseCheck,
                    batchCheck: batchCheck,
                    checkDateFormat: checkDateFormat,
                    checkNum: checkNum,
                    bindDefaultHandler:bindDefaultHandler
                }
            })(),

            tableToExcel: (function () {
                var uri = 'data:application/vnd.ms-excel;base64,',
                    template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
                    base64 = function (s) {
                        return window.btoa(unescape(encodeURIComponent(s)))
                    },
                    format = function (s, c) {
                        return s.replace(/{(\w+)}/g,
                            function (m, p) {
                                return c[p];
                            })
                    };

                return function (table, name) {
                    if (!table.nodeType) table = document.getElementById(table)
                    var ctx = {
                        worksheet: name || 'Worksheet',
                        table: table.innerHTML
                    }
                    window.location.href = uri + base64(format(template, ctx))
                }
            })()
        };

    }
);
define(
    '../epg2/EpgWeb.Dao',['require','exports','module'],function (require, exports, module) {
        EpgWeb.Dao = $.extend({}, Ancestor.Dao, {
            cfgName: {
                LiveType: "LiveType",
                LogType: "LogType",
                episodeGradeType: "EpisodeGradeType",
                liveProgramType: "LiveProgramType",
                liveChannelType: "LiveChannelType",
                getChannel: "getChannel"
            },
            channelId: null,
            getDataByName: function (targetName) {
                var responseData = EpgWeb.ajaxQueue.findResponseData(targetName);
                return responseData;
            },
            sendAjax: function (url, method, data, callback, authUrl) {
                var options = {
                    url: url,
                    dataType: 'json',
                    data: data,
                    type: method,
                    success: function (data) {
                        if (callback != null) {
                            callback.call(this, data);
                        }
                    },
                    error: function (data) {
                        if (callback != null) {
                            callback.call(this, data);
                        }
                    }
                };
                Ancestor.Dao.ajax(options, authUrl);
            },
            appendAuthUrl: function (options, authUrl) {
                options = $.extend({},options, {
                    beforeSend: function (request) {
                        var authBase = Ancestor.Util.getAuth('/vod/episodeLogList');
                        request.setRequestHeader('Sign', authBase.sign);
                        request.setRequestHeader("Time", authBase.clientTime);
                        request.setRequestHeader("From", authBase.from);
                        request.setRequestHeader("UserName", (auth.baseInfo.authInfo == null) ? "" : escape(auth.baseInfo.authInfo.userName).toLocaleLowerCase().replace(/%u/gi, '\\u'));
                    }
                })
                return options;
            },

            sendProxy: function (options, headers) {
                $.ajax(this.transToProxyOptions(options, headers));
            },
            transToProxyOptions: function (options, headers) {
                var requestData = {url: options.url, type: options.type, params: options.data, needCookie: true};
                if (headers != null) {
                    requestData.headers = headers;
                }
                var newOptions = {
                    url: EpgWeb.urlConfig.redirect,
                    type: "post",
                    dataType: "json",
                    timeout: options.timeout?options.timeout: 5000,
                    data: {"request": JSON.stringify(requestData), timeSign: new Date().getTime()},
                    success: function (data) {
                        options.success(data);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        options.error(null);
                    }
                }
                return newOptions;
            },
            doGet: function (url, data, callback) {
                var dataArr = [];
                for (var key in data) {
                    dataArr.push(key + "=" + data[key]);
                }

                var options = {
                    url: url,
                    dataType: 'json',
                    data: dataArr.join("&"),
                    type: 'get',
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                };
                $.ajax(options);
            },
            doAuthData: function (handlerObj) {
                if (auth == null) {
                    auth = Ancestor.Auth;
                }
                auth.getAuthData({tips: 1, url: handlerObj.url}, function (rt) {
                    if (rt == null) {
                        if (handlerObj.hasOwnProperty("doSuccess")) {
                            handlerObj.doSuccess();
                        }
                    } else {
                        if (handlerObj.hasOwnProperty("doError")) {
                            handlerObj.doError();
                        }
                    }
                    if (handlerObj.hasOwnProperty("doFinal")) {
                        handlerObj.doFinal();
                    }
                });
            },
//            checkJSVersion: function (data, callback) {
//                //method, data, callback, authUrl) {
//                this.sendAjax("/api/version/check", "post", {data:JSON.stringify(data)}, callback);
//            }
            notifyAlert: function (sendData, callback) {
                var url = EpgWeb.urlConfig.notifyAlertUrl;
                var options = {
                    type: "post",
                    url: url,
                    dataType: "json",
                    data: {data: JSON.stringify(sendData)},
                    success: function (data) {
                        callback.call(this, data);
                    },
                    error: function (data) {
                        callback.call(this, data);
                    }
                }
                Ancestor.Dao.ajax(options, "/notify/alertPlatform");
            }

        })
    }
);
define(
    '../epg2/EpgWeb.Task',['require','exports','module'],function (require, exports, module) {
        EpgWeb.Task = (function () {
            var handler = function(data,callback){
                if (callback != null) {
                    callback.call(this, data);
                }
            }
            var getConfigType = function (typeName, callback, regName) {
                if (regName == null) {
                    regName = typeName;
                }
                return {
                    regName: regName,
                    options: {
                        type: "get",
                        url: EpgWeb.urlConfig.configs,
                        dataType: "json",
                        data: {type: typeName},
                        success: function(data){
                            handler.call(this, data,callback);
                        },
                        error: function(data){
                            handler.call(this, data,callback);
                        }
                    }
                }
            }

            var getChannel = function (regName,params) {
                return {
                    regName:regName,
                    options: {
                        type: "post",
                        url: EpgWeb.urlConfig.channelGet,
                        dataType: "json",
                        data: params
                    }
                }
            }
            return {
                getConfigType: getConfigType,
                getChannel:getChannel
            }
        })()
    }
);
/**
 * Created by wangle on 2018/4/17.
 */
define(
    '../record/RecordCol',['require','exports','module'],function (require, exports, module) {
        window.RecordCol = window.RecordCol || {version: '1.0'};
        RecordCol.Constant = {
            baseApiUrl: "/api/",
            devMode: auth.dev(),
            thirdUrl_query_user: "http://lego.iqiyi.com/external/auth/auth-api/services/user/search",
            thirdUrl_channel_url:"http://lego.iqiyi.com/apis/channel/list"
        }
        RecordCol.urlConfig = (function () {
            var useUrl = RecordCol.Constant.baseApiUrl;
            var redirectUrl = useUrl + "redirect";
            var doColSaveUrl = useUrl + "recordRPC/col/save";
            var doColEditUrl = useUrl + "recordRPC/col/update";
            var doColDelUrl = useUrl + "recordRPC/col/delete";
            var getColUrl = useUrl + "recordRPC/col/list";
            var getColAuthUrl = useUrl + "recordRPC/col/authList";
            var getColUrlInfo = useUrl + "recordRPC/col/info";
            var getRecordChannelUrl = useUrl + "record/channel/list";
            return {
                redirectUrl: redirectUrl,
                doColSaveUrl: doColSaveUrl,
                doColEditUrl: doColEditUrl,
                doColDelUrl: doColDelUrl,
                getColUrl: getColUrl,
                getRecordChannelUrl:getRecordChannelUrl,
                getColUrlInfo: getColUrlInfo,
                getColAuthUrl:getColAuthUrl
            }
        })()
    }
);
/**
 * Created by wangle on 2018/4/17.
 */
define(
    '../record/RecordCol.Action',['require','exports','module'],function(require, exports, module){
        RecordCol.Action = (function() {
            var recordColList = null;
            function runColList(){
                if (!recordColList) {
                    recordColList = new RecordCol.Grid($.extend(true, {
                        $grid:$("#list"),
                        $container:$("#j-view-container"),
                        type: 0
                    }, {}));
                }
                recordColList.doInit();
                console.log('plan grid run');
            }
            return {
                runColList:runColList,
            }
        })();
    }
);

/**
 * Created by wangle on 2018/4/17.
 */
define('../record/RecordCol.Config',['require','exports','module'],function (require, exports, module) {
    RecordCol.Config = $.extend({}, {}, {
        TABLE_COLMODEL_CONFIG: {
            id: {
                name: "id",
                index: 'id',
                title: false,
                width: 100,
                align: "center",
                sortable: false
            },
            colName: {
                name: "colName",
                index: 'colName',
                title: false,
                width: 120,
                align: "center",
                sortable: false
            },
            channelId: {
                name: "channelId",
                index: 'channelId',
                title: false,
                width: 120,
                align: "center",
                sortable: false,
                hidden:true
            },
            channelName: {
                name: "channelName",
                index: 'channelName',
                title: false,
                width: 120,
                align: "center",
                sortable: false,
            },
            hasAuth: {
                name: "hasAuth",
                index: 'hasAuth',
                title: false,
                width: 80,
                align: "center",
                sortable: false,
                formatter: function (v, o, r) {
                    return RecordCol.Util.formatter.hasAuth(v, o, r);
                }
            },
            hasPublic: {
                name: "hasPublic",
                index: 'hasPublic',
                title: false,
                width: 80,
                align: "center",
                sortable: false,
                formatter: function (v, o, r) {
                    return RecordCol.Util.formatter.hasPublic(v, o, r);
                }
            },
            categoryId: {
                name: "categoryId",
                index: 'categoryId',
                title: false,
                width: 120,
                align: "center",
                sortable: false,
                formatter: function (v, o, r) {
                    return RecordCol.Util.formatter.category(v, o, r);
                }
            },
            opUser: {
                name: "opUser",
                index: 'opUser',
                title: false,
                width: 180,
                align: "center",
                sortable: false
            },
            createTime: {
                name: "createTime",
                index: 'createTime',
                title: false,
                width: 300,
                align: "center",
                sortable: false
            },
            operator_plan_list: {
                title: false,
                width: 100,
                align: "center",
                sortable: false,
                formatter: function (v, o, r) {
                    return RecordCol.Util.formatter.operator_plan_list(v, o, r);
                }
            },
        },

        TABLE_COLMODEL_AUTH_CONFIG: {
            cprVideoName: {
                name: "cprVideoName",
                index: 'cprVideoName',
                title: false,
                width: 200,
                align: "center",
                sortable: false
            },
            videoType: {
                name: "videoType",
                index: 'videoType',
                title: false,
                width: 80,
                align: "center",
                sortable: false
            },
            productDate: {
                name: "productDate",
                index: 'productDate',
                title: false,
                width: 150,
                align: "center",
                sortable: false,
            },

            authStartDate: {
                name: "authStartDate",
                index: 'authStartDate',
                title: false,
                width: 150,
                align: "center",
                sortable: false,
                // formatter: function (v, o, r) {
                //     return RecordCol.Util.formatter.hasAuth(v, o, r);
                // }
            },
            authEndDate: {
                name: "authEndDate",
                index: 'authEndDate',
                title: false,
                width: 150,
                align: "center",
                sortable: false,
                // formatter: function (v, o, r) {
                //     return RecordCol.Util.formatter.hasPublic(v, o, r);
                // }
            },
            blackOrWhite: {
                name: "blackOrWhite",
                index: 'blackOrWhite',
                title: false,
                width: 100,
                align: "center",
                sortable: false,
                formatter: function (v, o, r) {
                     return RecordCol.Util.formatter.auth(v, o, r);
                }
            },
            updatedTime: {
                name: "updatedTime",
                index: 'updatedTime',
                title: false,
                width: 150,
                align: "center",
                sortable: false
            },
        },

        COL_DATA_LIST: {
            url: RecordCol.urlConfig.getColUrl,
            loadBeforeSend: function (xhr, settings) {
                var auth = Ancestor.Util.getAuth("/recordRPC/col/list");
                xhr.setRequestHeader('Sign', auth.sign);
                xhr.setRequestHeader("Time", auth.clientTime);
                xhr.setRequestHeader("From", auth.from);
                return true;
            },
            multiselect: false,
            loadtext: '加载中...',
            loadui: 'block',
            rowNum: 20,
            mtype: "post",
            datatype: "local",
            prmNames: {
                page: "pageNo",
                rows: "pageSize"
            },
            colNames: ["栏目ID", "栏目名称", "频道id","频道","素材", "有无版权", "创建人", "创建时间", "操作"],
            colModel: ['id', "colName", "channelId", "channelName","categoryId", "hasAuth","opUser", "createTime", "operator_plan_list"],
            pager: "#pager"
        },

        AUTH_DATA_LIST: {
            url: RecordCol.urlConfig.getColAuthUrl,
            loadBeforeSend: function (xhr, settings) {
                var auth = Ancestor.Util.getAuth("/recordRPC/col/authList");
                xhr.setRequestHeader('Sign', auth.sign);
                xhr.setRequestHeader("Time", auth.clientTime);
                xhr.setRequestHeader("From", auth.from);
                return true;
            },
            multiselect: false,
            loadtext: '加载中...',
            loadui: 'block',
            rowNum: 10,
            mtype: "post",
            datatype: "local",
            prmNames: {
                page: "currentPage",
            },
            colNames: ["版权片名",       "分类",       "发行时间",    "开始时间",        "截止时间",    "名单类型",      "最后更新"],
            colModel: ["cprVideoName", "videoType", "productDate","authStartDate", "authEndDate","blackOrWhite","updatedTime"],
            pager: "#pagerAuth",
            jsonReader:{
                root:"data",
                page: "currentPage",
                records: "totalRecords",
                repeatitems : false
            }
        },
        CODE_SUC: "A00000"
    });
});
/**
 * Created by wangle on 2018/4/17.
 */
define(
    '../record/RecordCol.Dao',['require','exports','module'],function (require, exports, module) {

        RecordCol.Dao = $.extend({}, EpgWeb.Dao, {
            deleteRecordCol: function (sendData, handler) {
                this.sendAjax(RecordCol.urlConfig.doColDelUrl, "post", sendData, handler, "/recordRPC/col/delete");
            },
            addRecordCol: function (sendData, handler) {
                this.sendAjax(RecordCol.urlConfig.doColSaveUrl, "post", sendData, handler, "/recordRPC/col/save");
            },
            editRecordCol: function (sendData, handler) {
                this.sendAjax(RecordCol.urlConfig.doColEditUrl, "post", sendData, handler, "/recordRPC/col/update");
            },
            getRecordCol: function (entityId, handler) {
                this.sendAjax(RecordCol.urlConfig.getColUrl, "post", {id: entityId}, handler, "/recordRPC/col/list");
            },
            getRecordColInfo: function (sendData, handler) {
                this.sendAjax(RecordCol.urlConfig.getColUrlInfo, "post", sendData, handler, "/recordRPC/col/info");
            },
            getRecordChannelList :function(sendData,handler){
                this.sendAjax(RecordCol.urlConfig.getRecordChannelUrl ,"post",sendData,handler,"/record/channel/list");
            }
        });
        RecordCol.Dao.cfgName = {
            logType: "ticket_log",
            workType: "ticket_worker"
        }
    }
);

/**
 * Created by wangle on 2018/4/17.
 */
define(
    '../record/RecordCol.Grid',['require','exports','module'],function (require, exports, module) {
        RecordCol.Grid = function (options) {
            this.dao = RecordCol.Dao;
            this.config = RecordCol.Config;
            this.util = RecordCol.Util;
            this.task = RecordCol.Task;
            this.options = options || {};
        };
        Com.inherits(RecordCol.Grid, Ancestor.Grid).extend({
            doInit: function () {
                var self = this;
                var taskArr = [];
                taskArr.push(self.task.getLegoCategory("lego_category"))
                $.each(taskArr, function (index, element) {
                    EpgWeb.ajaxQueue.push(element.regName, element.options);
                })

                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    self.bindEvent();
                    self.initSuggest();
                    self.initGrid();
                    self.initSelect();
                    self.initDlg();
                    self.initAuthDlg();

                    var urlParams = self.getUrlParam();
                    if(urlParams['channelId'] && urlParams['channelName']){
                        self.query(urlParams['channelId']);
                        $('input[name="LIKES_col.channelName"]').val(urlParams['channelName']);
                    }else{
                        self.query();
                    }
                })
                EpgWeb.ajaxQueue.startLoad();
            },
            bindEvent: function () {
                var self = this;
                var parentDom = $("form[role=addForm]");
                $("button[name=add_col_btn]").bind("click", function (event) {
                    RecordCol.Util.sendAddColPlan();
                    $(".ui-dialog-title").html("新建栏目");
                })
                $("button[name=edit_col_btn]").bind("click", function (event) {
                    RecordCol.Util.sendEditColPlan();
                    $(".ui-dialog-title").html("新建栏目");
                })
                $("button[name=cancel_btn]").bind("click", function (event) {
                    $("form[role=addForm]").dialog("close")
                    $(".ui-dialog-title").html("新建栏目");
                })

                $("button[name=open_new_dlg_btn]").bind("click", function (event) {
                    $("form[role=addForm]").dialog("open");
                    $("form[role=addForm]")[0].reset();
                    var urlParams = self.getUrlParam();
                    if(urlParams['channelId'] && urlParams['channelName']){
                        $("form[role=addForm]").find("input[name=channel_name]").suggest("setValue", {id: urlParams['channelId'], label: urlParams['channelName']}).attr('disabled','disabled');
                    }
                    parentDom.find("button[name=add_col_btn]").show();
                    parentDom.find("button[name=edit_col_btn]").hide();

                })

                $("button[name=query_btn]").bind("click", function (event) {
                    self.query();
                })
                
                $("button[name=queryA]").bind("click", function(){
                    $("form[role=authForm]").dialog("open");
                    $("#ui-id-7").html('版权查询');
                    $("input[name=pcrName]").val("");
                    $("#authList").jqGrid("clearGridData");
                });

                $("button[name=queryAuth]").bind("click", function(){
                    self.authQuery();
                });

            },

            initSuggest: function () {
                var channelSuggest = {
                    options: {
                        ajaxSettings: {
                            beforeSend: function (request) {
                                var authBase = Ancestor.Util.getAuth("/record/channel/list");
                                request.setRequestHeader('Sign', authBase.sign);
                                request.setRequestHeader("Time", authBase.clientTime);
                                request.setRequestHeader("From", authBase.from);
                                request.setRequestHeader("UserName", (auth.baseInfo.authInfo == null) ? "" : escape(auth.baseInfo.authInfo.userName).toLocaleLowerCase().replace(/%u/gi, '\\u'));
                            }
                        },
                        source: RecordCol.urlConfig.getRecordChannelUrl,
                        method: "post",
                        autoFilter: false,
                        autoFocus: false,
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var jsonObj = {'LIKES_channelName': $.trim(term), 'NEQI_status': 0};
                            return {"dataMode": "simple", paramsObj: JSON.stringify(jsonObj)}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = json.data == null ? null : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data.result, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["id"];
                                itemData[options.labelKey] = item["channelName"]
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item.label;
                        }
                    }
                }

                var colSuggest = {
                    options: {
                        ajaxSettings: {
                            beforeSend: function (request) {
                                var authBase = Ancestor.Util.getAuth("/recordRPC/col/list");
                                request.setRequestHeader('Sign', authBase.sign);
                                request.setRequestHeader("Time", authBase.clientTime);
                                request.setRequestHeader("From", authBase.from);
                                request.setRequestHeader("UserName", (auth.baseInfo.authInfo == null) ? "" : escape(auth.baseInfo.authInfo.userName).toLocaleLowerCase().replace(/%u/gi, '\\u'));
                            }
                        },
                        source: "/api/recordRPC/col/list",
                        method: "post",
                        autoFilter: false,
                        autoFocus: false,
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var jsonObj = {LIKES_colName: $.trim(term)};
                            return {"dataMode": "simple", paramsObj: JSON.stringify(jsonObj)}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = json.data == null ? null : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data.result, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["id"];
                                itemData[options.labelKey] = item["colName"]
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item.label;
                        }
                    }
                }

                colSuggest.options.clearInvalid = false;
                $('input[name="LIKES_col.colName"]').suggest(colSuggest.options);
                $("input[name=channel_name]").suggest(channelSuggest.options);
                channelSuggest.options.clearInvalid = false;
                $('input[name="LIKES_col.channelName"]').suggest(channelSuggest.options);


            },
            initGrid: function (options) {
                var orOpt = options;
                var self = this;
                self.$grid = self.options.$grid;
                var params = self.getParam();

                var gridConfig = self.getGridConfig(self.config.COL_DATA_LIST);
                options = $.extend(true, {
                    mtype: 'post',
                    postData: $.extend(true, {}, params)
                }, gridConfig, options);
                self.$grid.jqGrid(options);

                var $authGrid = $("#authList");

                gridConfig = self.getGridConfig(self.config.AUTH_DATA_LIST, self.config.TABLE_COLMODEL_AUTH_CONFIG);
                orOpt = $.extend(true, {
                    mtype: 'get',
                }, gridConfig, orOpt);
                $authGrid.jqGrid(orOpt);
            },
            query: function (channelId,callback) {
                var self = this;
                var $grid = self.$grid;
                var params = self.getParam();
                var urlParams = self.getUrlParam();

                if(channelId){
                    var pp = JSON.parse(params['paramsObj']);
                    pp['EQI_channelId'] = channelId;
                    params ={'paramsObj': JSON.stringify(pp)} ;
                }

                var parentDom = $("form[role=addForm]");
                $(".ui-dialog-title").html("新建栏目");
                params.sortType = "desc";
                $grid.jqGrid('setGridParam', {
                    page: 1,
                    datatype: "json",
                    postData: params
                }).trigger('reloadGrid');
            },


            getParam: function () {
                var params = {};
                var inputArr = $('form[role="queryForm"]').find("input[role=query-text]")
                $.each(inputArr, function (i, element) {
                    if (element.value.trim().length > 0) {
                        params [$(element).attr("name")] = element.value.trim()
                    }
                });
                var selectArr = $('form[role="queryForm"]').find("select[role=query-select]")
                $.each(selectArr, function (i, element) {
                    if (element.name != "query-repeat-code") {
                        if (element.value.trim().length > 0) {
                            params [$(element).attr("name")] = element.value.trim()
                        }
                    }
                });
                params["EQI_col.status"] = 1;
                return {paramsObj: JSON.stringify(params)};
            },
            initSelect: function () {
                var resultData = RecordCol.Dao.getDataByName("lego_category");
                var filterArr = [];
                if (resultData != null) {
                    $.each(resultData.data, function (i, element) {
                        if (element.categoryConfig != null && element.categoryConfig.isIntoSearch == 1) {
                            filterArr.push({key: element.id, val: element.name})
                        }
                    })
                    var selectJDom = $("select[name='category_id']");
                    $("<option value=''></option>").appendTo(selectJDom);
                    $.each(filterArr, function (index, obj) {
                        $("<option>", {
                            value: obj.key,
                            html: obj.val
                        }).appendTo(selectJDom);
                    });
                }
            },
            initDlg: function () {
                $("form[role=addForm]").dialog({
                    title: "新建栏目",
                    autoOpen: false,
                    height: 400,
                    width: 800,
                    modal: true,
                });
            },

            initAuthDlg: function () {
                $("form[role=authForm]").dialog({
                    autoOpen: false,
                    height: 600,
                    width: 1200,
                    modal: true,
                })
            },

            initModifyDlg: function (type) {
                if (type == "edit") {

                } else if (type == "add") {

                }
            },
            getUrlParam: function(){
                var url = location.href;
                var params = {};
                if(url.indexOf('?')!=-1) {
                    var info = url.split('?')[1].split('&');
                    var channelId = info[0].split('=')[1];
                    var channelName = decodeURI(info[1].split('=')[1]);
                    params['channelId'] = channelId;
                    params['channelName'] = channelName;
                }

                return params;
            },

            authQuery: function (channelId,callback) {
                var self = this;
                var $grid = $("#authList");
                var self = this;
                var pcrName = $('input[name="pcrName"]').val().trim();
                if(!pcrName || pcrName == ''){
                    RecordCol.Util.logTips({theme: "error", content: "版权名称不能为空"});
                    return;
                }

                $grid.jqGrid('setGridParam', {
                    page: 1,
                    datatype: "json",
                    postData: {name:pcrName}
                }).trigger('reloadGrid');
            },
        });
    }
);
/**
 * Created by wangle on 2018/4/17.
 */
define('../record/RecordCol.Util',['require','exports','module'],function (require, exports, module) {
    RecordCol.Util = $.extend(true, {}, EpgWeb.Util, {
        formatter: {
            operator_plan_list: function (v, o, r) {
                var htmlArr = [];
                htmlArr.push("<a href='javascript:;' onclick='RecordCol.Util.openColModifyDlg(" + r.id + ")'>修改</a>&nbsp;&nbsp;&nbsp;");
                htmlArr.push("<a href='javascript:;' onclick='RecordCol.Util.delCol(" + r.id + ")'>删除</a>");
                return htmlArr.join("");
            },
            hasAuth: function (v, o, r) {
                return v == 1 ? "有" : "无";
            },
            hasPublic: function (v, o, r) {
                return v == 1 ? "是" : "否";
            },
            category: function (v, o, r) {
                var resultData = RecordCol.Dao.getDataByName("lego_category");
                var ret = "";
                $.each(resultData.data, function (i, element) {
                    if (element.id == v) {
                        ret = element.name;
                        return false;
                    }
                })
                return ret;
            },
            auth: function (v, o, r) {
                return v == 0 ? "黑名单":"白名单";
            }
        },
        reloadHandler: function (data) {
            if (data != null) {
                EpgWeb.Plugin.showTips({content: data.msg, type: data.code == "A00000" ? "success" : "error"});
                if (data.code == "A00000") {
                    $("#list").trigger("reloadGrid")
                }
            } else {
                console.log("callbackHandler no return data");
            }
        },
        checkValidColMode: function (entity) {
            console.log(entity)
            if (isNaN(entity.channelId) || entity.channelName=='') {
                RecordCol.Util.logTips({ theme: "error", content: "请填写有效频道"});
                return false;
            }
            if (entity.colName =='') {
                RecordCol.Util.logTips({ theme: "error", content: "请填写有效栏目"});
                return false;
            }
            if (entity.categoryId =='') {
                RecordCol.Util.logTips({ theme: "error", content: "请填写有效分类"});
                return false;
            }
            return true;
        },
        prepareColMode: function () {
            var sendData = {};
            var parentDom = $("form[role=addForm]");
            sendData.channelId = parseInt(parentDom.find("input[name=channel_name]").suggest("getValue"));
            sendData.channelName = parentDom.find("input[name=channel_name]").val();

            sendData.colName = parentDom.find("input[name=col_name]").val().trim();
            sendData.status = 1;
            var selectArr = parentDom.find("select[role=query-select]")
            // $.each(selectArr, function (i, element) {
            //     if (element.name != "query-repeat-code") {
            //         if (element.value.trim().length > 0) {
            //             // params [$(element).attr("name")] = element.value.trim()
            //             sendData.categoryId = element.value.trim();
            //         }
            //     }
            // });
            sendData.categoryId = parentDom.find("select[name=category_id]").val();
            sendData.hasAuth = parseInt(parentDom.find("select[name=hasAuth]").val());
            sendData.hasPublic = parseInt(parentDom.find("select[name=enable]").val());
            return sendData;
        },
        sendAddColPlan: function () {
            var sendData = RecordCol.Util.prepareColMode();
            var flag = RecordCol.Util.checkValidColMode(sendData);
            if (flag) {
                $("form[role=addForm]").dialog("close")
                RecordCol.Dao.addRecordCol({data: JSON.stringify(sendData)}, function (data) {
                    if (data != null && data.code == "A00000") {
                        RecordCol.Util.reloadHandler(data)
                    } else {
                        EpgWeb.Plugin.showTips({type: "error", content: "创建失败"});
                    }
                })
            }
        },
        sendEditColPlan: function () {
            var sendData = RecordCol.Util.prepareColMode();
            var tempId = parseInt($("form[role=addForm]").find("input[name=edit_col_id]").val());
            if (tempId > 0) {
                sendData.id = tempId;
            }
            var flag = RecordCol.Util.checkValidColMode(sendData);
            if (flag) {
                $("form[role=addForm]").dialog("close");
                RecordCol.Dao.editRecordCol({data: JSON.stringify(sendData)}, function (data) {
                    if (data != null && data.code == "A00000") {
                        RecordCol.Util.reloadHandler(data)
                    } else {
                        EpgWeb.Plugin.showTips({type: "error", content: "创建失败"});
                    }
                })
            }
        },
        delCol: function (entityId) {
            console.log("wait to do");
            SystemDialog.queryConfirm("确认删除？", function (flag) {
                if (flag === true) {
                    RecordCol.Dao.deleteRecordCol({id: entityId}, function (data) {
                        RecordCol.Util.reloadHandler(data);
                    })
                }
            })
        },
        doAddFormReset: function () {
            var parentDom = $("form[role=addForm]");
            parentDom[0].reset();
            parentDom.find("input[name=col_name]").val(null);
            parentDom.find("input[name=channel_name]").val(null);
            parentDom.find("select[name=hasAuth]").val(null);
            parentDom.find("select[name=enable]").val(null);
            parentDom.find("select[name=category_id]").val(null);
        },
        logTips: function (options) {
            EpgWeb.Plugin.showTips(options);
        },
        doAddFormFillData: function (element) {
            var parentDom = $("form[role=addForm]");
            parentDom.find("input[name=edit_col_id]").val(element.id);
            parentDom.find("input[name=col_name]").val(element.colName);
            parentDom.find("input[name=channel_name]").suggest("setValue", {id: element.channelId, label: element.channelName}).attr('disabled','disabled');
            parentDom.find("select[name=hasAuth]").val(element.hasAuth);
            parentDom.find("select[name=enable]").val(element.hasPublic);
            parentDom.find("select[name=category_id]").val(element.categoryId);
        },
        openColModifyDlg: function (entityId) {
            RecordCol.Util.doAddFormReset();
            var parentDom = $("form[role=addForm]");
            if (entityId > 0) {
                RecordCol.Dao.getRecordColInfo({id: entityId}, function (data) {
                    if (data != null && data.code == "A00000") {
                        // RecordCol.Dao.getRecordChannelList({paramsObj: JSON.stringify({EQL_id: data.data.channelId}), dataMode: "simple"}, function (gdata) {
                        //     if (gdata != null && gdata.code == "A00000") {
                        //         parentDom.dialog("open");
                        //         parentDom.find("button[name=add_plan_btn]").hide();
                        //         data.data.channelName = gdata.data.result[0].channelName;
                        //         RecordCol.Util.doAddFormFillData(data.data);
                        //     }
                        // })
                        RecordCol.Util.doAddFormFillData(data.data);
                        parentDom.dialog("open");
                        parentDom.find("button[name=add_col_btn]").hide();
                        parentDom.find("button[name=edit_col_btn]").show();
                    } else {
                        RecordCol.Util.logTips({theme: "error", content: "访问数据失败"});
                    }
                });
            } else {
                parentDom.dialog("open");
                parentDom.find("button[name=edit_col_btn]").hide();
                parentDom.find("button[name=add_col_btn]").hide();
            }
            $(".ui-dialog-title").html("修改栏目");
        }
    });
});
/**
 *
 */
define(
    '../record/RecordCol.Task',['require','exports','module'],function (require, exports, module) {
        RecordCol.Task = (function () {
            var getLegoCategory = function (typeName,  regName) {
                if (regName == null) {
                    regName = typeName;
                }
                var requestData = {url: RecordCol.Constant.thirdUrl_channel_url, type: "get", needCookie: true};
                return {
                    regName: regName,
                    options: {
                        type: "post",
                        url: "/api/redirect",
                        dataType: "json",
                        data: {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                    }
                }
            }
            return {
                getLegoCategory:getLegoCategory
            }
        })()
    }
);
/**
 * Created by wangle on 2018/4/17.
 */
define(
    'recordCol', [
        "../entrance_record/Ancestor",
        "../entrance_record/Ancestor.Auth",
        "../entrance_record/Ancestor.Grid",
        "../entrance_record/Ancestor.Config",
        "../entrance_record/Ancestor.Util",
        "../entrance_record/Ancestor.Dao",
        "../epg2/EpgWeb",
        "../epg2/EpgWeb.Util",
        "../epg2/EpgWeb.Plugin",
        "../epg2/EpgWeb.Dao",
        "../epg2/EpgWeb.Task",
        "../record/RecordCol",
        "../record/RecordCol.Action",
        "../record/RecordCol.Config",
        "../record/RecordCol.Dao",
        "../record/RecordCol.Grid",
        "../record/RecordCol.Util",
        "../record/RecordCol.Task"
    ],

    function () {
        console.log('recordCol load done:', 'recordCol');
        if (SystemDialog && SystemDialog.initSystemDialog) {
            SystemDialog.initSystemDialog();
        }
    }
);

